# -*- coding: utf-8 -*-
import os 
import time 
from tinydb import TinyDB, Query
from urllib.parse import quote, unquote
from os.path import join, getsize 
from heapq import nlargest 
 
import requests
from bs4 import BeautifulSoup
import json
import urllib.request
import re #写正则表达式要导入的

fileName = 'default.json'
urlValue = 'https://fuliba2023.net/'
def returnArr(url):
    questionString = ''
    answerString = ''
    realURL = ''
    if 'question' in url and 'answer' in url:
        arr = url.split('/')
        defIndex = len(arr) + 1
        for iString in arr:
            if defIndex == 1:
                questionString = iString.replace('\n', '');
                defIndex = len(arr) + 1
            if defIndex == 2:
                answerString = iString.replace('\n', '');
                defIndex = len(arr) + 1
            if iString == 'question':
                defIndex = 1;
            if iString == 'answer':
                defIndex = 2;
    
    if '-' in url and '知乎' in url:
        arrURL = url.split('https://www.zhihu.com')
        realURL = 'https://www.zhihu.com' + arrURL[len(arrURL) - 1]
    else:
        realURL = url 
    
    if questionString != '' and answerString != '' and realURL != '':
        print(questionString)
        print(answerString)
        netWork(realURL, questionString, answerString)



def netWork(url, questionString, answerString):
    headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"}
    response = requests.get(url,headers=headers)
    print('--------------------------------------->')
    # print(response.text)
    try :
        if not '后自动跳转至回答所在的问题页' in response.text:
            beautifulSoup = BeautifulSoup(response.text, 'html.parser')
            resultStrring = beautifulSoup.find('script', id = 'js-initialData')
            
            frame = str(resultStrring)
            newFrame = frame.replace('</script>', '')
            target = ">"
            index = newFrame.index(target)
            result = newFrame[index+1:]
            jsonModel = json.loads(result)
            # print(jsonModel['initialState']['entities']['questions'])
                
            tmpTitle = jsonModel['initialState']['entities']['questions'][questionString]['title']
            tmpContent = jsonModel['initialState']['entities']['answers'][answerString]['content']
            # print(tmpTitle)
            # print(tmpContent)
            if 'img' in tmpContent or 'IMG' in tmpContent:
                re_img = r'<[img|IMG].*?>' 
                re_img_rc = r'.+?data-original="(\S+)"' 
                img_url_list = []
                img_list= re.findall(re_img, tmpContent)#找到所有的img标签
                print(img_list)
                # if len(img_list) == 0:
                    
                for tag in img_list:
                    if '<i>' in tag:
                        continue;
                    if 'data-original' not in tag:
                        continue;
                    imgPath = re.findall(re_img_rc, tag)[0]
                    print(imgPath)
                    img_url_list.append(imgPath)#找到所有的img_url
                    
                arrPic = list(set(img_url_list))
                for item in arrPic:
                    downLoadPNG(item)
                    time.sleep(1);
                
                print('一共发现{}图片--------------------->'.format(len(arrPic)))
                # print()
        elif '后自动跳转至回答所在的问题页' in response.text:
            print('文章已经被删除-------------------->')  
        else:
            print('知乎被发现了-------------------->')  
    except Exception as e :
        print('报错了-------------------->{error}'.format(error=e)) 
    

def downLoadPNG(url):
    imgSavePath = 'trash3'
    print('url----------------------------------->{url}'.format(url=url))
    firstTag = url.split('?')[0].split('/')
    imgTypeArr = firstTag[len(firstTag) - 1].split('.')
    imgType = imgTypeArr[len(imgTypeArr) - 1]
    img_data = requests.get(url).content
    filepath = os.path.join(imgSavePath)
    fileName = "{a}/{b}.{c}".format(a=filepath, b=str(int(time.time())), c=imgType)
    if not os.path.exists(imgSavePath):
            os.makedirs(filepath)
    with open(fileName, 'wb') as f:
        f.write(img_data)



def insertItem(item):
    db = TinyDB(fileName)
    table = db.table('fuliba')
    fuliba = Query()
    res = table.search(fuliba.name == item['name'])
    if len(res) == 0:
        table.insert(item)
        dingdingTalk(item['name'] + ': ' + item['link'])
    else:
        print('已存在')
        
# 钉钉机器人的调用
def dingdingTalk(msg):
    HEADERS = {"Content-Type": "application/json;charset=utf-8"}
    key = "e9b59afdcad471cd70b8e4016f2752a03084d66c34abea961f2ebf8a3d785a30"
    url = "https://oapi.dingtalk.com/robot/send?access_token=%s" % key
    data_info = {
        "msgtype": "text",
        "text": {
            # "content": "Log: \n" + msg
            "content": msg
        },
        "isAtAll": True
    }

    value = json.dumps(data_info)
    response = requests.post(url, data=value, headers=HEADERS)

def notificationToken(titleMsg, message):
    # tkoen = 'WwuUQD5ZNv7Aq9A67AswCN'#晓粉的
    tkoen = 'CM3QdttP2tJrGSSJ9ybEqS'  # 我的
    first = quote(titleMsg, 'utf-8')
    second = quote(message, 'utf-8')
    nowTmp = 'https://api.day.app/{}/{}/{}'.format(tkoen, first, second)
    res = requests.post(nowTmp)

    if res.json()['code'] == 200:
        print('发送成功')
    else:
        print(res.text)
 



url = """

"""

returnArr(url)
